<?php

namespace app\meizhuangapi\controller;

use app\meizhuangapi\model\Category as CategoryModel;
use app\meizhuangapi\model\WxappCategory as WxappCategoryModel;
use think\Db;
use app\api\controller\Category as CategorysCon;
/**
 * 商品分类控制器
 */
class Category extends CategorysCon
{
    /**
     * 分类页面
     * @return array
     * @throws \think\exception\DbException
     */
    public function index()
    {
        // 分类模板
        $templet = WxappCategoryModel::detail();
        // 商品分类列表
        $list = array_values(CategoryModel::getCacheTree());

        //处理二级分类所属板块问题
        if($list){
            foreach ($list as $k=>$v){
                $upload=Db::name('upload_file')->where(['file_id'=>['in',$v['meizhuang_imges']]])->select()->toArray();
                foreach ($upload as $ks=>$vs){
                    $upload[$ks]['file_path']=$vs['file_url'].'/'.$vs['file_name'];
                }
                $list[$k]['images']=$upload;
                unset($list[$k]['image']);
                if(isset($v['child'])&&!empty($v['child'])){
                    $list[$k]['child']=$this->array_group_by($v['child'],'bankuai_id');
                }
            }
        }
        return $this->renderSuccess(compact('templet', 'list'));
    }

    private function array_group_by($arr, $key){
        $grouped = [];
        foreach ($arr as $value) {
            //将板块id为值
            $names=Db::name('meizhuang_bankuai')->where(['id'=>$value[$key]])->field('name')->find();
            $grouped[$names['name']][] = $value;
        }
        if (func_num_args() > 2) {
            $args = func_get_args();
            foreach ($grouped as $key => $value) {
                $parms = array_merge([$value], array_slice($args, 2, func_num_args()));
                $grouped[$key] = call_user_func_array('array_group_by', $parms);
            }
        }
        return $grouped;
    }

}
